import PateoSearchForm from '@/components/common/PateoSearchForm';
import { filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { AddModal } from './Modal/addModal';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { ColumnsType } from 'antd/es/table';
import Ellipsis from '@/components/Ellipsis';
import { mapProvidersOpt } from '..';
import moment from 'moment';
import { DATE_HMS } from '@/support/constant/common';
import { ViewModal } from './Modal/viewModal';

@connect((state: any) => ({
  serviceCapabilityDetail: state.serviceCapabilityDetail,
  loading: state.loading.effects['serviceCapabilityDetail/postFetchPage'],
}))
export default class ServiceCapabilityDetail extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };
  state = {
    formValues: {},
    formData: {},
    addModalVisible: false,
    viewModalVisible: false,
    dataClassOpt: [],
    accountData: JSON.parse(sessionStorage.getItem('serviceCapabilityDetailData') ?? '{}'),
  };
  componentDidMount() {
    const { dispatch } = this.props;
    // console.log('this.context.dicData', this.context.dicData);
    // const a = findDicByCode(this.context.dicData, 'deviceStatus');
    // console.log('aaaaaaaaaa', a);
    this.fetchPage();
  }
  handleFormReset = () => {
    this.state.formValues = {};
    // this.setState({ formValues: this.state.formValues });
  };
  closeModal = (refresh = false) => {
    this.setState({
      addModalVisible: false,
      viewModalVisible: false,
      formData: {},
    });
    if (refresh) {
      const { formValues } = this.state;
      this.fetchPage(formValues);
    }
  };
  handleFreshPage = () => {
    this.fetchPage();
  };
  handleTableChange = (pagination: any, filters: any = {}) => {
    const { current, pageSize } = pagination;
    const params = {
      current: current,
      pageSize: pageSize,
      ...filters,
    };
    this.fetchPage(params);
  };
  fetchPage = (params = {}) => {
    const { dispatch } = this.props;
    const { formValues, accountData } = this.state;
    dispatch({
      type: 'serviceCapabilityDetail/postFetchPage',
      payload: {
        url: '/msaggregationmap/serviceconfigration/list',
        accountId: accountData.id,
        ...params,
        ...formValues,
      },
    });
  };

  render() {
    const { addModalVisible, formData, viewModalVisible, accountData } = this.state;
    const {
      serviceCapabilityDetail: {
        pageData: { list, pagination },
      },
      loading,
    } = this.props;

    const columns: ColumnsType<any> = [
      {
        title: '序号',
        dataIndex: 'rowNumber',
        width: 40,
      },
      {
        title: '服务能力',
        dataIndex: 'serviceName',
        width: 150,
        ellipsis: true,
      },

      {
        title: 'key',
        dataIndex: 'keyNum',
        width: 150,
        render: (value, record, index) => {
          return (
            <Button
              onClick={() => this.setState({ viewModalVisible: true, formData: record })}
              type="link"
            >
              {value}
            </Button>
          );
        },
        ellipsis: true,
      },

      {
        title: '添加时间',
        dataIndex: 'createTime',
        width: 150,
        ellipsis: true,
        render: (v, record) => {
          return moment(v).format(DATE_HMS);
        },
      },

      {
        title: '操作',
        dataIndex: '操作',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'serviceCapabilityDetail-opt',
              onConfirm: () => {
                this.setState({ addModalVisible: true, formData: record });
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'serviceCapabilityDetail-opt',
              Popconfirm: true,
              message: '是否确认删除该服务能力，删除后该账号该服务能力下的key将同步删除?',
              onConfirm: () => {
                const { dispatch } = this.props;
                dispatch({
                  type: 'serviceCapabilityDetail/postObjWithRes',
                  payload: {
                    url: '/msaggregationmap/serviceconfigration/delete',
                    accountId: accountData.id,
                    account: accountData.account,
                    serviceCode: record.serviceCode,
                  },
                  callback: res => {
                    if (res.statusCode === '0') {
                      message.success('删除成功');
                      this.fetchPage();
                    }
                  },
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} pathname={this.props.location.pathname} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: '服务能力',
        key: 'serviceName',
      },
    ];
    return (
      <div>
        <Card style={{ fontWeight: 800 }}>
          {accountData.id
            ? `${mapProvidersOpt.find(t => t.value === accountData.suppliersMap)?.label}   账号: ${
                accountData.account
              }`
            : null}
        </Card>
        <Card bordered={false}>
          {/* search form */}
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'serviceCapabilityDetail/postFetchPage',
              url: '/msaggregationmap/serviceconfigration/list',
              extraArgs: {},
            }}
            dispatchFn={this.fetchPage}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          {/* add */}
          <div>
            {filterAuth(
              'serviceCapabilityDetail-opt',
              this.context.permissions,
              this.props.location.pathname,
            ) ? (
              <div className="my_newItem">
                <Button
                  icon={
                    <PlusOutlined
                      onPointerEnterCapture={undefined}
                      onPointerLeaveCapture={undefined}
                    />
                  }
                  type="primary"
                  size="small"
                  onClick={() => this.setState({ addModalVisible: true })}
                >
                  配置服务能力
                </Button>
              </div>
            ) : null}
          </div>

          {/* table */}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'auto' }}
          />
        </Card>
        <AddModal modalVisible={addModalVisible} closeModal={this.closeModal} formData={formData} />
        <ViewModal
          modalVisible={viewModalVisible}
          closeModal={this.closeModal}
          formData={formData}
        />
      </div>
    );
  }
}
